package com.pricetag.pricetagandroid;

import java.util.concurrent.atomic.AtomicBoolean;

import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.pricetag.helpers.Constants;
import com.pricetag.search.SearchHandler;
import com.pricetag.search.SearchRecord;

@SuppressWarnings("deprecation")
public class SearchDetailTabActivity extends TabActivity {
	private String searchRecordID;
	private LayoutInflater inflater;
	private LinearLayout overviewRowContainerLayout;
	private SearchRecord searchRecord;
	private TextView contentView;
	private Intent intentGoogle;
	private TabHost tabHost;
	private Spinner spinner;
	private ArrayAdapter<String> adapter;
	private String[] adapterNames = { "Crowd Sourced", "Machine Learnt" };

	TextView tv1;
	TextView tv2;

	private AtomicBoolean isRunning = new AtomicBoolean(true);
	private int updateInterval = 1000;
	private UpdateDetailTabTask updateDetailTabTask = null;

	private SearchDetailTabActivity me;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		me = this;
		setContentView(R.layout.activity_search_detail_tab);

		Bundle bundle = this.getIntent().getExtras();
		searchRecordID = (String) bundle.get(Constants.SEARCH_RECORD_ID);
		searchRecord = SearchHandler.getSearchRecord(searchRecordID);

		addTabs();
	}

	@Override
	public void onStart() {
		super.onStart();

		inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		overviewRowContainerLayout = (LinearLayout) this.findViewById(R.id.overview_row_container_layout);
		overviewRowContainerLayout.removeAllViews();
		overviewRowContainerLayout.setBackgroundColor(Color.GRAY);
		this.setupOverviewRowContainerLayout();

		this.isRunning.set(true);
		if (updateDetailTabTask != null) {
			updateDetailTabTask.cancel(true);
		}
		updateDetailTabTask = new UpdateDetailTabTask();
		updateDetailTabTask.execute(null, null, null);
	}

	@Override
	public void onStop() {
		super.onStop();
		this.isRunning.set(false);

		if (updateDetailTabTask != null) {
			updateDetailTabTask.cancel(true);
		}
	}

	private void setupOverviewRowContainerLayout() {

		View overviewRowView = inflater
				.inflate(R.layout.search_history_overview_row, overviewRowContainerLayout, false);
		TextView dateView = (TextView) overviewRowView.findViewById(R.id.search_history_row_date_textview);
		contentView = (TextView) overviewRowView.findViewById(R.id.search_history_row_content_textview);
		ImageView imageView = (ImageView) overviewRowView.findViewById(R.id.search_history_row_thumbnail_imageview);

		Bitmap thumbnail = BitmapFactory.decodeByteArray(searchRecord.getThumbnail(), 0,
				searchRecord.getThumbnail().length);
		imageView.setImageBitmap(thumbnail);
		imageView.getLayoutParams().width = 200;

		dateView.setText(searchRecord.getDateCreated().toLocaleString());
		dateView.setBackgroundColor(Color.GRAY);

		if (searchRecord.getLocalImageDBProductName() == null) {
			contentView.setText("Waiting for Data".toUpperCase());
		} else {
			contentView.setText(searchRecord.getLocalImageDBProductName().toUpperCase());
		}
		contentView.setBackgroundColor(Color.GRAY);
		contentView.setTextSize(15);
		overviewRowContainerLayout.addView(overviewRowView);

		LinearLayout infoArea = (LinearLayout) this.findViewById(R.id.info_area);
		spinner = new Spinner(this);
		adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, this.adapterNames);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) {
				switch (pos) {
				// case 0:
				//
				// if (searchRecord.getLocalImageDBProductName() == null) {
				// contentView.setText("Waiting for Data".toUpperCase());
				// } else {
				// contentView.setText(searchRecord.getLocalImageDBProductName().toUpperCase());
				// }
				//
				// break;
				case 0:
					if (searchRecord.getIqEngineProductName() == null) {
						contentView.setText("Waiting for Data".toUpperCase());
					} else {
						contentView.setText(searchRecord.getIqEngineProductName().toUpperCase());
					}

					break;
				case 1:
					if (searchRecord.getGoogleGoggleProductName() == null) {
						contentView.setText("Waiting for Data".toUpperCase());
					} else {
						contentView.setText(searchRecord.getGoogleGoggleProductName().toUpperCase());
					}

					break;
				}
				intentGoogle.putExtra(Constants.LOCATION_SELECTION, pos);
				tv1.setBackgroundColor(Color.LTGRAY);
				tv2.setBackgroundColor(Color.WHITE);
				tabHost.setCurrentTab(0);
				tabHost.setCurrentTab(1);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}

		});
		infoArea.addView(spinner);
	}

	private void addTabs() {
		tabHost = getTabHost();
		tabHost.setBackgroundColor(Color.GRAY);
		tv1 = new TextView(tabHost.getContext());
		tv1.setText("Local Store");
		tv1.setGravity(Gravity.CENTER);
		tv1.setBackgroundColor(Color.WHITE);
		tv1.setHeight(60);

		tv2 = new TextView(tabHost.getContext());
		tv2.setText("Price from Internet");
		tv2.setGravity(Gravity.CENTER);
		tv2.setBackgroundColor(Color.LTGRAY);
		tv2.setHeight(60);

		tv1.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getDownTime() > 1000) {
					tv1.setBackgroundColor(Color.WHITE);
					tv2.setBackgroundColor(Color.LTGRAY);
					tabHost.setCurrentTab(0);
					return true;
				}
				return false;
			}

		});

		tv2.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getDownTime() > 1000) {
					tv2.setBackgroundColor(Color.WHITE);
					tv1.setBackgroundColor(Color.LTGRAY);
					tabHost.setCurrentTab(1);
					return true;
				}
				return false;
			}

		});

		Intent intentLocal = new Intent().setClass(this, LocalStoreSearchResultActivity.class).addFlags(
				Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intentLocal.putExtra(Constants.SEARCH_RECORD_ID, searchRecordID);

		TabSpec tabSpecLocal = tabHost.newTabSpec("Local").setIndicator(tv1).setContent(intentLocal);

		intentGoogle = new Intent().setClass(this, GoogleProductSearchResultActivity.class).addFlags(
				Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intentGoogle.putExtra(Constants.SEARCH_RECORD_ID, searchRecordID);
		intentGoogle.putExtra(Constants.LOCATION_SELECTION, 0);

		TabSpec tabSpecGoogle = tabHost.newTabSpec("Google").setIndicator(tv2).setContent(intentGoogle);

		tabHost.addTab(tabSpecLocal);
		tabHost.addTab(tabSpecGoogle);
		tabHost.setCurrentTab(0);

	}

	public void switchToSearchHistoryListActivity(View view) {
		Intent intent = new Intent(this, SearchHistoryListActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
		this.startActivity(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_search_detail, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menu_settings:
			switchToSettingsActivity();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void switchToSettingsActivity() {
		Intent intent = new Intent(this, SettingsActivity.class);
		this.startActivity(intent);
	}

	private class UpdateDetailTabTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			try {
				Thread.sleep(updateInterval);
			} catch (Exception e) {
			}
			searchRecord = SearchHandler.getSearchRecord(searchRecordID);
			return null;
		}

		@Override
		protected void onPostExecute(Void results) {
			adapterNames[0] = (searchRecord.getIqEngineProductName() == null) ? "Crowd Sourced" : searchRecord
					.getIqEngineProductName();
			adapterNames[1] = (searchRecord.getGoogleGoggleProductName() == null) ? "Machine Learnt" : searchRecord
					.getGoogleGoggleProductName();

			adapter.notifyDataSetChanged();
			if (isRunning.get()) {
				updateDetailTabTask = new UpdateDetailTabTask();
				updateDetailTabTask.execute(null, null, null);
			}
		}
	}

}
